package com.ruoyi.common.core.mybatisplus;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

@MappedTypes({Long.class})
@MappedJdbcTypes(JdbcType.BIGINT)
public class LongToDateTypeHandler extends BaseTypeHandler<String> {

    private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        try {
            ps.setLong(i, dateFormat.parse(parameter).getTime() / 1000);
        } catch (ParseException e) {
            ps.setLong(i, new Date().getTime());
        }
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        long time = rs.getLong(columnName) * 1000;
        return rs.wasNull() ? null : dateFormat.format(new Date(time));
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        long time = rs.getLong(columnIndex) * 1000;
        return rs.wasNull() ? null : dateFormat.format(new Date(time));
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        long time = cs.getLong(columnIndex) * 1000;
        return cs.wasNull() ? null : dateFormat.format(new Date(time));
    }

    // 可以根据需要添加其他方法
}